package com.wn.icloud.provider.uac.controller;

import com.wn.icloud.auth.client.annotation.IgnoreUserToken;
import com.wn.icloud.common.msg.TableResultResponse;
import com.wn.icloud.common.utils.UploadUtil;
import com.wn.icloud.provider.uac.entity.Cover;
import com.wn.icloud.provider.uac.service.CoverBiz;
import com.wn.icloud.provider.uac.service.dto.CoverDTO;
import com.wn.icloud.provider.uac.vo.CoverVO;
import com.wn.icloud.rest.BaseController;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

@Controller
@RequestMapping("/content/cover")
public class CoverController extends BaseController<CoverBiz, Cover> {


    @RequestMapping(value = "/coverAll", method = RequestMethod.GET)
    @ResponseBody
    public TableResultResponse<CoverVO> getCoverAll(CoverDTO dto) {
        TableResultResponse<CoverVO> list = baseBiz.selectCoverAll(dto);
        return list;
    }

    @PostMapping(value = "/addCover")
    @ResponseBody
    public void addCover(@Valid @RequestBody CoverDTO coverDTO) {
        baseBiz.addCover(coverDTO);
    }

    @PostMapping(value = "/updateCover")
    @ResponseBody
    public void updateCover(@Valid @RequestBody CoverDTO coverDTO) {
        baseBiz.updateCover(coverDTO);
    }

    @DeleteMapping(value = "/deleteByIds")
    @ResponseBody
    public void deleteByIds(String ids) {
        baseBiz.deleteCover(ids);
    }


    @IgnoreUserToken
    @PostMapping("/uploadImage")
    public String uploadImage(HttpServletRequest request){

        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        MultipartFile multipartFile = multipartHttpServletRequest.getFile("file");
        String fileName = multipartFile.getOriginalFilename();
        InputStream inputStream = null;
        try {
            inputStream = multipartFile.getInputStream();
        }catch (IOException e){
            throw new RuntimeException("读取文件时出错，请重试", e);
        }
        UploadUtil.uploadFtpFile(inputStream,fileName);
        String path = "/upload/"+fileName;
        return path;
    }

    @IgnoreUserToken
    @GetMapping("/previewImage")
    public void previewImage(HttpServletResponse response, String filePath) {
        FTPClient ftpClient = new FTPClient();
        InputStream in = null;
        OutputStream outputStream = null;
        try {
            UploadUtil.startFtpClient(ftpClient);
        }catch (IOException e){
            e.printStackTrace();
            throw new RuntimeException("启动FTP客户端出错！", e);
        }
        try {
            String filepath =   filePath;
            in = ftpClient.retrieveFileStream(filepath);
            byte[]  bytes = IOUtils.toByteArray(in);
            //手动关闭 再调用completePendingCommand
            if(in != null){
                in.close();
            }
            //completePendingCommand()会一直在等FTP Server返回226 Transfer complete，但是FTP Server只有在接受到InputStream执行close方法时，才会返回。所以先要执行close方法
            ftpClient.completePendingCommand();
            //获得输入流
            in = new ByteArrayInputStream(bytes);
            //获得文件后缀
            String picType = filepath.split("\\.")[1];
            BufferedImage bufImg = null;
            bufImg = ImageIO.read(in);
            System.out.println(bufImg);
            outputStream = response.getOutputStream();
            // 将内存中的图片通过流动形式输出到客户端
            ImageIO.write(bufImg, picType, outputStream);
            System.out.println("已写出图片流-----------------------------------");
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("FTP客户端出错！", e);
        } finally {
            try {
                if(in!=null){in.close();}
                ftpClient.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException("关闭FTP连接发生异常！", e);
            }
        }
    }

}
